package com.util;

import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.math.ec.ECPoint;

import java.math.BigInteger;

public class getKeyUnit {

    public static void getKey(byte[] ckey, ECPoint PK, BigInteger sk) {
        // Perform scalar multiplication: keyPoint = sk * PK
        ECPoint keyPoint = PK.multiply(sk).normalize();

        // Get the x and y coordinates of the resulting keyPoint
        BigInteger x = keyPoint.getAffineXCoord().toBigInteger();
        BigInteger y = keyPoint.getAffineYCoord().toBigInteger();

        // Convert coordinates to byte arrays and concatenate them
        byte[] xBytes = bigIntegerToBytes(x, 32); // Assuming 32 bytes for x
        byte[] yBytes = bigIntegerToBytes(y, 32); // Assuming 32 bytes for y
        byte[] tmp2 = new byte[64]; // 32 bytes for x + 32 bytes for y
        System.arraycopy(xBytes, 0, tmp2, 0, 32);
        System.arraycopy(yBytes, 0, tmp2, 32, 32);

        // Hash the concatenated byte array
        SHA256Digest digest = new SHA256Digest();
        digest.update(tmp2, 0, tmp2.length);
        digest.doFinal(ckey, 0);
    }

    private static byte[] bigIntegerToBytes(BigInteger bigInt, int length) {
        byte[] bytes = bigInt.toByteArray();
        if (bytes.length == length) {
            return bytes;
        } else if (bytes.length > length) {
            // Truncate leading byte
            byte[] tmp = new byte[length];
            System.arraycopy(bytes, bytes.length - length, tmp, 0, length);
            return tmp;
        } else {
            // Pad with leading zeros
            byte[] tmp = new byte[length];
            System.arraycopy(bytes, 0, tmp, length - bytes.length, bytes.length);
            return tmp;
        }
    }
}
